#!/usr/bin/env python
# Copyright (C) 2007 by Xyhthyx <xyhthyx@gmail.com>

# This file is part of Parcelle.

# Parcelle is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.

# Parcelle is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

try:
	import xml.dom.minidom
	import xml.dom.ext
except ImportError:
	print 'Pease install the python-xml module.'
	sys.exit(1)
import common

# Keeps a list of X most recently
# added clipboard/primary items
class Recent:
	
	def __init__(self):
		
		# FIXME: Make user able to change the size
		# and make it get items from original list
		# instead of making a copy
		self.size = 15
		
		self.data = []
		
		# Open saved XML file
		try:
			document = xml.dom.minidom.parse(common.RECENT_FILE)
			items = document.getElementsByTagName('item')
			settings = document.getElementsByTagName('recent')
			try:
				# Get size option
				self.size = int(settings[0].attributes['size'].nodeValue)
			except:
				pass
			# Get items
			for item in items:
				self.data[len(self.data):] = [item.childNodes[0].nodeValue]
		except:
			pass
		
	# Set the size
	def set_size(self, size=15):
		
		self.size = size
		# Slice if number of items larger than size
		if len(self.data) > size:
			self.data = self.data[len(self.data)-size:]
		
		self.save_recent()
	
	# Clear the list
	def clear(self):
		
		self.data[:] = []
		self.save_recent()
	
	# Returns entire list
	def get_data(self):
		
		if self.data == []:
			return None
		else:
			return self.data
	
	# Returns particular item in list
	def get_item(self, item):
		
		return self.data[item]
	
	# Insert a new item and delete oldest one
	def push(self, text):
		
		if not text:
			return
		
		if len(self.data) < self.size:
			self.data[len(self.data):] = [text]
		else:
			self.data = self.data[1:]
			self.data[len(self.data):] = [text]
		
		self.save_recent()
	
	# Save recent data to XML file
	def save_recent(self):
		
		# Create XML document and append main element
		document = xml.dom.minidom.Document()
		ele_recent = document.createElement('recent')
		ele_recent.setAttribute('size', str(self.size))
		document.appendChild(ele_recent)
		# Append each item
		for each in self.data:
			ele_item = document.createElement('item')
			ele_item.appendChild(document.createTextNode(str(each)))
			ele_recent.appendChild(ele_item)
		
		# Save document
		try:	
			xml.dom.ext.PrettyPrint(document, open(common.RECENT_FILE, 'w'))
		except IOError:
			print 'Could not save XML document.'
